<template>
  <section style="padding:10px;">
    <!--查询-->
    <el-form class="ad-form-query" :inline="true" :model="filters" @submit.native.prevent>
      <el-form-item>
        <el-input v-model="filters.label" placeholder="菜单名" clearable @keyup.enter.native="onGetList">
          <template #prefix>
            <i class="el-input__icon el-icon-search" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-search" @click="onGetList">查询</el-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['admin_syspermission_add'])">
        <el-button type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      row-key="id"
      :data="viewTree"
      :default-expand-all="false"
      :expand-row-keys="expandRowKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      border

      :header-cell-style="{background:'#f9f9f9'}"
      style="width: 100%;margin:10px 0;"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="name" label="菜单名" width="180" />
      <el-table-column prop="code" label="编码" width />
      <el-table-column prop="path" label="视图地址" width />
      <el-table-column prop="icon" label="图标" width="120">
        <!-- <template #default="{row}">
          <i :class="row.icon" />
        </template> -->
        <template slot-scope="scope">
          <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
        </template>
      </el-table-column>

      <el-table-column prop="sort" label="排序" width="120" />
      <el-table-column prop="enabled" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.enabled ? 'success' : 'info'" disable-transitions>
            {{ row.enabled ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="说明" width />
      <el-table-column v-if="checkPermission(['admin_syspermission_update','admin_syspermission_delete'])" label="操作" width="180">
        <template #default="{ $index, row }">
          <el-button v-if="checkPermission(['admin_syspermission_update'])" type="success" icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
          <my-confirm-button v-if="checkPermission(['admin_syspermission_delete'])" type="delete" icon="el-icon-delete" :loading="row._loading" @click="onDelete($index, row)" />
        </template>
      </el-table-column>
    </el-table>

    <!--新增窗口-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      width="40%"
      @close="onCloseAddForm"
    >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
        <el-form-item prop="parentId" label="上级菜单">
          <el-cascader
            :key="addFormKey"
            v-model="addForm.parentId"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id',label:'name' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="菜单名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="视图地址" prop="path">
          <el-input v-model="addForm.path" auto-complete="off" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="addForm.code" auto-complete="off" />
        </el-form-item>
        <el-form-item label="图标" prop="Icon">
          <el-popover
            placement="bottom-start"
            width="600"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input slot="reference" v-model="addForm.icon" placeholder="点击选择图标" readonly>
              <svg-icon
                v-if="addForm.icon"
                slot="prefix"
                :icon-class="addForm.icon"
                class="el-input__icon"
                style="height: 32px;width: 16px;"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="addForm.sort" auto-complete="off" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="addForm.enabled" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="说明" prop="remarks">
          <el-input v-model="addForm.remarks" type="textarea" rows="2" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
        </div>
      </template>
    </el-dialog>

    <!--编辑窗口-->
    <el-dialog
      title="编辑"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      @close="onCloseeditForm"
    >
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px" size="medium">
        <el-form-item prop="parentId" label="上级菜单">
          <el-cascader
            :key="addFormKey"
            v-model="editForm.parentId"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id',label:'name' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="菜单名" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="视图地址" prop="path">
          <el-input v-model="editForm.path" auto-complete="off" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="editForm.code" auto-complete="off" />
        </el-form-item>
        <el-form-item label="图标" prop="Icon">
          <el-popover
            placement="bottom-start"
            width="600"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input slot="reference" v-model="editForm.icon" placeholder="点击选择图标" readonly>
              <svg-icon
                v-if="editForm.icon"
                slot="prefix"
                :icon-class="editForm.icon"
                class="el-input__icon"
                style="height: 32px;width: 16px;"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="editForm.sort" auto-complete="off" />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="editForm.enabled" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="说明" prop="remarks">
          <el-input v-model="editForm.remarks" type="textarea" rows="2" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="editFormValidate" :loading="editLoading" @click="onEditSubmit" />
        </div>
      </template>
    </el-dialog>
  </section>
</template>

<script>
import { listToTree, getTreeParents } from '@/utils'
import IconSelect from '@/components/IconSelect'
import {
  removeMenu,
  editMenu,
  addMenu,
  getMenuList,
  getMenu
} from '@/api/admin/permission'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Menu',
  components: {
    MyConfirmButton, IconSelect
  },
  data() {
    return {
      filters: {
        label: ''
      },
      viewTree: [],
      expandRowKeys: [],
      listLoading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        parentId: [{ required: true, message: '请选择上级菜单', trigger: 'change' }],
        path: [{ required: true, message: '请输入视图地址', trigger: 'blur' }],
        name: [{ required: true, message: '请输入菜单名', trigger: 'blur' }]
      },
      // 编辑界面数据
      editForm: {
        id: '',
        parentId: '',
        path: '',
        label: '',
        enabled: '0',
        description: '',
        icon: undefined
      },
      editFormKey: 1,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        parentId: [{ required: true, message: '请选择上级菜单', trigger: 'change' }],
        path: [{ required: true, message: '请输入视图地址', trigger: 'blur' }],
        code: [{ required: true, message: '请输入唯一编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入菜单名', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        parentId: '',
        path: '',
        enabled: '1',
        remarks: '',
        icon: undefined,
        code: '',
        sort: 0
      },
      addFormKey: 1,
      modules: [],
      deleteLoading: false
    }
  },
  mounted() {
    this.onGetList()
  },
  methods: {

    // 选择图标
    selected(name) {
      this.addForm.icon = name
      this.editForm.icon = name
    },

    // 获取列表
    async onGetList() {
      const para = {
        name: this.filters.label
      }
      this.listLoading = true
      const res = await getMenuList(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      const list = _.cloneDeep(res.data)
      const keys = list.filter(l => l.parentId === 0).map(l => l.id + '')
      this.expandRowKeys = keys

      this.modules = listToTree(_.cloneDeep(list), {
        id: '0',
        parentId: '',
        name: '根节点'
      })
      list.forEach(l => {
        l._loading = false
      })

      const tree = listToTree(list)
      this.sels = []
      this.viewTree = tree
    },
    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      const res = await getMenu({ id: row.id })

      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.viewTree, row.id)
        const parentIds = parents.map(p => p.id)
        parentIds.unshift(0)
        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editForm.enabled = data.enabled.toString()
        this.editFormVisible = true
        ++this.editFormKey
      }
    },
    onCloseeditForm() {
      this.$refs.editForm.resetFields()
      ++this.editFormKey
    },
    // 显示新增界面
    onAdd() {
      this.addFormVisible = true
    },
    onCloseAddForm() {
      this.$refs.addForm.resetFields()
      ++this.addFormKey
    },
    // 编辑
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onEditSubmit() {
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      if (para.id === para.parentId) {
        this.$message({
          message: '所属模块不能是自己！',
          type: 'error'
        })
        this.editLoading = false
        return
      }

      const res = await editMenu(para)
      this.editLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.onGetList()
    },
    // 新增
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.parentId = para.parentId.pop()
      const res = await addMenu(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.onGetList()
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const res = await removeMenu(JSON.stringify(row.id))

      row._loading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: '成功删除！',
        type: 'success'
      })
      this.onGetList()
    }

  }
}
</script>
